using System;
using System.IO;
using UnityEngine;
using LS.Digitize;

namespace LS.Digitize
{
    public sealed class Vector2Serializer: CompoundSerializer<Vector2>
    {
        public Vector2Serializer() : base(typeof(Vector2),typeof(float))
        {
            
        }
        
        public override void WriteData(IWriter writer, Vector2 obj)
        {
            ISerializer subSerializer = SubSerializer;
            using (writer.WriteObjectScope())
            {
                if (subSerializer is PrimitiveSerializer<float> ps)
                {
                    using (writer.WritePropertyScope("x"))
                        ps.WriteData(writer, obj.x);
                    
                    using (writer.WritePropertyScope("y"))
                        ps.WriteData(writer, obj.y);
                }
                else
                {
                    using (writer.WritePropertyScope("x"))
                        subSerializer.Write(writer, obj.x);
                    
                    using (writer.WritePropertyScope("y"))
                        subSerializer.Write(writer, obj.y);
                }
            }
        }

        public override Vector2 ReadData(IReader reader)
        {
            ISerializer subSerializer = SubSerializer;
            Vector2 target = default;
            using (var objScope = reader.ReadObjectScope())
            {
                string propertyName = null;
                if (subSerializer is PrimitiveSerializer<float> ps)
                {
                    propertyName = reader.ReadPropertyName();
                    float x = ps.ReadData(reader);
                    propertyName = reader.ReadPropertyName();
                    float y = ps.ReadData(reader);
                    target = new Vector2(x, y);
                }
                else
                {
                    propertyName = reader.ReadPropertyName();
                    float x = (float)subSerializer.Read(reader);
                    propertyName = reader.ReadPropertyName();
                    float y = (float)subSerializer.Read(reader);
                    target = new Vector2(x, y);
                }
            }

            return target;
        }
        
        public override void ReadInto(IReader reader, ref Vector2 obj)
        {
            obj = ReadData(reader);
        }
    }
}